<template>
  <div class="wrapper">
    <div id="building">
      <div class="login_box">
        <!-- logo头像 -->
        <div class="logo_box">
          <img src="../assets/3.png" alt="" />
        </div>
        <!-- 表单登录 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          label-width="0px"
          class="login_form"
          :rules="loginFormRules"
        >
          <el-form-item prop="account">
            <el-input v-model="loginForm.account" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              placeholder="请输入密码"
            />
          </el-form-item>
          <el-form-item>
            <div style="display: flex">
              <el-input prefix-icon="el-icon-key" v-model="loginForm.validCode" style="width: 50%;" placeholder="请输入验证码:"></el-input>
              <ValidCode @input="createValidCode" />
            </div>
          </el-form-item>
          <el-form-item class="btns" style="margin-left: 14%;">
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="default" @click="resetLoginForm">重置</el-button>
            <el-button type="success" @click="registeropen">注册</el-button>
            <el-button type="warning" @click="forGet">忘记密码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <!-- 新增区域 -->
  <el-dialog v-model="dialogVisible" title="注册" width="50%">
      <el-form label-width="70px" size="small">
        <el-form-item label="头像" style="margin-left: 36%;">
          <el-upload
            class="avatar-uploader"
            ref="upload"
            action="#"
            :show-file-list="false"
            :on-change="handleChange"
            :auto-upload="false"
            list-type="picture-card"
          >
            <img
              v-if="form.userphoto"
              :src="form.userphoto"
              class="avatar"
              width="148"
              height="148"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input size="small" v-model="form.account" type="text" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input size="small" v-model="form.password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            clearable
            v-model="form.sex"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in sexs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input size="small" v-model="form.phone" type="text" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-input size="small" v-model="form.birth" type="date" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input size="small" v-model="form.address" type="text" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址">
          <el-input
              v-model="form.email"
              type="text"
              autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="register">确 认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 忘记密码邮箱验证模态框 -->
    <el-dialog v-model="dialogVisibleforget" title="找回密码" width="50%">
      <el-form-item label="邮箱地址">
          <el-input v-model="forme.email" type="text" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="验证码：">
          <el-input v-model="forme.code" type="text" autocomplete="off" style="width: 80px; margin-right: 20px;"></el-input>
          <el-button type="primary" @click="getcode(this.forme.email)">获取验证码</el-button>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleforget = false">取 消</el-button>
          <el-button type="primary" @click="getPassword(this.forme.code)">确 认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 忘记密码修改模态框 -->
    <el-dialog v-model="dialogVisiblepassword" title="修改密码" width="50%">
      <el-form-item label="新  密  码">
          <el-input v-model="formpassword.password" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码">
          <el-input v-model="formpassword.newpassword" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisiblepassword = false">取 消</el-button>
          <el-button type="primary" @click="updataPassword">确 认</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script>
import ValidCode from "@/components/validCode";
export default {
  name: "LoginView",
  components: {ValidCode},
  data() {
    return {
      userid : 0,
      Toldpassword : '',
      formpassword:{
        password : '',
        newpassword : '',
      }, 
      newcode:'',
      loginForm: {
        account: "",
        password: "",
        validCode: "",
      },
      dialogVisible: false,
      dialogVisibleforget:false,
      dialogVisiblepassword: false,
      validCode:'',
      form: {},
      forme:{
        email:'',
        code:''
      },
      sexs: [
        {
          value: 0,
          label: "女",
        },
        {
          value: 1,
          label: "男",
        },
      ],
      //添加表单验证规则对象
      loginFormRules: {
        //验证用户名是否合法
        //注意：名称必须跟loginForm中绑定的属性名一致
        account: [
          {
            required: true,
            message: "用户名不能为空，请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不为为空，请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //修改密码方法
    updataPassword(){
      if(this.formpassword.newpassword == this.formpassword.password){
        const utilMd5 = require("../components/utils/md5");
        this.formpassword.newpassword = utilMd5.hexMD5(this.formpassword.newpassword);
        this.$http.post("/user/updatepassword?id="+this.userid+"&newpassword="+this.formpassword.newpassword).then(res=>{
          if(res.data.status == 200){
            this.dialogVisibleforget = false,
            this.dialogVisiblepassword = false,
            this.$message.success("修改成功");
          }else{
            this.$message.error("修改失败");
          }
        })
      }else{
        this.$message.error("两次输入不一致！");
        this.formpassword.newpassword = '',
        this.formpassword.password = ''
      }
    },
    //打开修改密码页面
    getPassword(code){
      //对比code看验证码对不对
      if(this.newcode == code){
        this.dialogVisiblepassword = true
      }else{
        this.$message.error("验证码不对");
        this.form.code = '';
      }
    },
    createValidCode(data){
      this.validCode = data
    },
    //将邮箱地址传输至后端获取验证码
    getcode(email){
      if(email==''){
        this.$message.error("请输入邮箱");
        return
      }
      this.$http.get("/user/email/"+email).then(res=>{
        if(res.data.status == 200){
          this.userid = Number(res.data.data.userid);
          this.newcode = res.data.data.email;
          this.$message.success("获取成功！");
        }else{
          this.$message.error(res.data.$message);
        }
      })
      
    },
    //忘记密码邮箱验证设置新密码页面
    forGet(){
      //点击打开忘记密码模态框
      this.dialogVisibleforget=true
    },
    //注册用户方法
    register() {
      if(this.file == null){
        return this.$message.error("请上传头像")
      }
      if(this.form.email == null){
        return this.$message.error("请填写邮箱")
      }
      if(this.form.account == null){
        return this.$message.error("请填写用户名")
      }
      if(this.form.password == null){
        return this.$message.error("请填写密码")
      }
      let fromdata = new FormData();
      fromdata.append("file", this.file.raw);
      this.$http.post("/oss/upload", fromdata).then((ress) => {
        if (ress.data.status == 200) {
          this.form.userphoto = ress.data.data;
          const utilMd5 = require('../components/utils/md5');
          this.form.password = utilMd5.hexMD5(this.form.password);
          this.$http.post("/user/register", this.form).then((res) => {
            if (res.data.status == 200) {
              this.$message.success("注册成功")
                this.dialogVisible = false,
                this.form = {}
            } else {
              if(res.data.status == 201){
                this.form.account = '';
                this.form.password = '';
              }
              if(res.data.status == 202){
                this.form.email = '';
                this.form.password = '';
              }
              this.$message.error(res.data.message);
            }
          });
        } else {
          this.$message.error(ress.data.message);
          return false;
        }
      });
    },
    handleChange(file) {
      const isJPG = file.raw.type.indexOf("image") !== -1;
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
      }
      this.form.userphoto = file.url;
      this.file = file;
    },
    //注册用户框打开方法
    registeropen() {
      this.form = {};
      this.dialogVisible = true;
    },
    //重置表单
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields(); //重置表单
    },
    login() {
      this.$refs.loginFormRef.validate((valid) => {
          if (!valid) return;
          if(valid){
            if(!this.loginForm.validCode){
              this.$message.error("请填写验证码");
              return;
            }
            if (this.loginForm.validCode.toLowerCase() !== this.validCode.toLowerCase()){
              this.$message.error("验证码错误");
              return;
            }
          }
          //登录
          const utilMd5 = require('../components/utils/md5');
          this.loginForm.password = utilMd5.hexMD5(this.loginForm.password);
          this.$http.post("/user/login", this.loginForm).then((res) => {
            if (res.data.status == 200) {
              this.$message.success(res.data.message);
              //token 保存到sessionStorage中
              window.sessionStorage.setItem("token", res.data.token);
              //存储用户信息到浏览器
              window.sessionStorage.setItem("user",JSON.stringify(res.data.data)
              );
              this.$router.push("/chat");
            } else {
              this.$message.error(res.data.message);
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 监听回车键执行事件
    keyDown (e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.login() // 需要执行的方法方法
      }
    }
  },
  // 绑定监听事件
  mounted () {
    window.addEventListener('keydown', this.keyDown)
  },
  // 销毁事件
  destroyed () {
    window.removeEventListener('keydown', this.keyDown, false)
  }
};
</script>

<style>
.wrapper {
  background: url("../assets/4.jpg");
  width: 100%;
  height: 100%;
  position: fixed;
  background-size: 100% 100%;
  background-position: center;
  position: relative;
}
#building {
  opacity: 0.8;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.logo_box {
  height: 180px;
  width: 210px;
  border-radius: 70%;
  padding: 10px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
}
.logo_box img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #eee;
}
.btns {
  display: flex;
  justify-content: center;
}
.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
</style>